package com.eleadmin.damon.biz.impl;

import com.eleadmin.damon.utils.results.BaseDao;
import com.eleadmin.damon.biz.DataBaseBiz;
import com.eleadmin.damon.entity.DataBaseTable;
import com.eleadmin.damon.result.ColumnsResult;
import com.eleadmin.damon.result.TableResult;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据层实现类
 *
 * @author : Doman
 * @version ：1.0
 * @date : 2023-05-06 10:49:33
 */
@Repository
public class DataBaseBizImpl extends BaseDao implements DataBaseBiz {

    @Override
    public List<TableResult> tableNames(DataBaseTable dataBaseTable) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<TableResult> rm = new BeanPropertyRowMapper<TableResult>(TableResult.class);

        StringBuffer sql = new StringBuffer("select table_name,table_comment,create_time from information_schema.TABLES ");
        sql.append(" where TABLE_SCHEMA=:database ");
        sql.append(" and instr(table_name,:tableName)>0 ");
        map.put("database", dataBaseTable.getDatabase());
        map.put("tableName", dataBaseTable.getTableName());
        getMapParameter(sql, map);
        return jdbcTemplate.query(sql.toString(), map, rm);
    }

    @Override
    public TableResult  tableName(DataBaseTable dataBaseTable) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<TableResult> rm = new BeanPropertyRowMapper<TableResult>(TableResult.class);
        StringBuffer sql = new StringBuffer("select table_name,table_comment,create_time from information_schema.TABLES ");
        sql.append(" where TABLE_SCHEMA=:database ");
        sql.append(" and table_name=:tableName ");
        map.put("database", dataBaseTable.getDatabase());
        map.put("tableName", dataBaseTable.getTableName());
        getMapParameter(sql, map);
        return jdbcTemplate.queryForObject(sql.toString(), map, rm);
    }
    @Override
    public List<ColumnsResult> columns(DataBaseTable dataBaseTable) {
        Map<String, String> map = new HashMap<String, String>();
        RowMapper<ColumnsResult> rm = new BeanPropertyRowMapper<ColumnsResult>(ColumnsResult.class);
        StringBuffer sql = new StringBuffer("select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT ");
        sql.append("from information_schema.COLUMNS ");
        sql.append("where table_name = :table_name and table_schema = :database");
        sql.append(" order by ORDINAL_POSITION ");
        map.put("database", dataBaseTable.getDatabase());
        map.put("table_name", dataBaseTable.getTableName());
        getMapParameter(sql, map);
        return jdbcTemplate.query(sql.toString(), map, rm);
    }


}
